<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
                <!-- 账号输入框 -->
                <el-form-item label="账号" prop="account">
                    <el-input
                        v-model="formData.account"
                        :disabled="formData.root == 1"
                        placeholder="请输入账号"
                        clearable
                    />
                </el-form-item>
                <!-- 管理员头像 -->
                <el-form-item label="头像">
                    <div>
                        <div class="avatar-upload-container">
                            <div class="avatar-preview" v-if="formData.avatar">
                                <img :src="formData.avatar" alt="头像预览" class="avatar-image" />
                            </div>
                            <div class="avatar-placeholder" v-else>
                                <el-icon :size="48" color="#ccc">
                                    <Avatar />
                                </el-icon>
                                <p>点击上传头像</p>
                            </div>
                            <el-upload
                                ref="uploadRef"
                                class="avatar-uploader"
                                :show-file-list="false"
                                :before-upload="beforeAvatarUpload"
                                :http-request="handleAvatarUpload"
                                accept="image/*"
                            >
                                <el-button type="primary" size="small" :loading="avatarUploading">
                                    {{ avatarUploading ? '上传中...' : '更换头像' }}
                                </el-button>
                            </el-upload>
                        </div>
                        <div class="form-tips">建议尺寸：100*100px，支持jpg，jpeg，png格式</div>
                    </div>
                </el-form-item>

                <!-- 名称输入框 -->
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入名称" clearable />
                </el-form-item>
                <!-- <el-form-item label="归属部门" prop="deptId">
                    <el-tree-select
                        class="flex-1"
                        v-model="formData.deptId"
                        :data="optionsData.dept"
                        clearable
                        multiple
                        node-key="id"
                        :props="{
                            value: 'id',
                            label: 'name',
                            disabled(data: any) {
                                return data.status !== 1
                            }
                        }"
                        check-strictly
                        :default-expand-all="true"
                        placeholder="请选择上级部门"
                    />
                </el-form-item>
                <el-form-item label="岗位" prop="jobsId">
                    <el-select
                        class="flex-1"
                        v-model="formData.jobsId"
                        clearable
                        multiple
                        placeholder="请选择岗位"
                    >
                        <el-option
                            v-for="(item, index) in optionsData.jobs"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item> -->

                <!-- 角色选择框 -->
                <el-form-item label="角色" prop="roleId" v-if="formData.root != 1">
                    <el-select
                        v-model="formData.roleId"
                        :disabled="formData.root == 1"
                        class="flex-1"
                        multiple
                        placeholder="请选择角色"
                        clearable
                    >
                        <el-option
                            v-for="(item, index) in optionsData.role"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <!-- 密码输入框 -->
                <el-form-item label="密码" prop="password">
                    <el-input
                        v-model="formData.password"
                        show-password
                        clearable
                        placeholder="请输入密码"
                    />
                </el-form-item>

                <!-- 确认密码输入框 -->
                <el-form-item label="确认密码" prop="password_confirm">
                    <el-input
                        v-model="formData.password_confirm"
                        show-password
                        clearable
                        placeholder="请输入确认密码"
                    />
                </el-form-item>

                <!-- 管理员状态 -->
                <el-form-item label="管理员状态" v-if="formData.root != 1">
                    <el-switch v-model="formData.disable" :active-value="0" :inactive-value="1" />
                </el-form-item>

                <!-- 多处登录 -->
                <el-form-item label="多处登录">
                    <div>
                        <el-switch
                            v-model="formData.multipoint_login"
                            :active-value="1"
                            :inactive-value="0"
                        />
                        <div class="form-tips">允许多人同时在线登录</div>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance, UploadRequestOptions } from 'element-plus'
import { Avatar } from '@element-plus/icons-vue'
import axios from 'axios'
import SparkMD5 from 'spark-md5'

import { deptAll } from '@/api/org/department'
import { jobsAll } from '@/api/org/post'
import { adminAdd, adminDetail, adminEdit } from '@/api/perms/admin'
import { roleAll } from '@/api/perms/role'
import { multipartInit } from '@/api/setting/user'
import Popup from '@/components/popup/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import feedback from '@/utils/feedback'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const uploadRef = ref()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 头像上传状态
const avatarUploading = ref(false)
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑管理员' : '新增管理员'
})
const formData = reactive({
    id: '',
    account: '',
    name: '',
    deptId: [],
    jobsId: [],
    roleId: [],
    avatar: '',
    password: '',
    password_confirm: '',
    disable: 0,
    multipoint_login: 1,
    root: 0
})
const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
        if (!value) callback(new Error('请再次输入密码'))
        if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
    }
    callback()
}

const roleIdValidator = (rule: object, value: string, callback: any) => {
    if (formData.root) {
        callback()
    } else {
        if (formData.roleId.length) {
            callback()
        } else {
            callback(new Error('请选择角色'))
        }
    }
}
const formRules = reactive({
    account: [
        {
            required: true,
            message: '请输入账号',
            trigger: ['blur']
        }
    ],
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ],
    roleId: [
        {
            required: true,
            validator: roleIdValidator
        }
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: ['blur']
        }
    ] as any[],
    password_confirm: [
        {
            required: true,
            message: '请输入确认密码',
            trigger: ['blur']
        },
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ] as any[]
})
const { optionsData } = useDictOptions<{
    role: any[]
    jobs: any[]
    dept: any[]
}>({
    role: {
        api: roleAll
    },
    jobs: {
        api: jobsAll
    },
    dept: {
        api: deptAll
    }
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await adminEdit(formData) : await adminAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (row: any) => {
    formRules.password = []
    formRules.password_confirm = [
        {
            validator: passwordConfirmValidator,
            trigger: 'blur'
        }
    ]
    const data = await adminDetail({
        id: row.id
    })
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

/**
 * 计算文件MD5
 */
const calculateFileMD5 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
        const spark = new SparkMD5.ArrayBuffer()
        const fileReader = new FileReader()
        const chunkSize = 10 * 1024 * 1024 // 10MB
        let currentChunk = 0
        const totalChunks = Math.ceil(file.size / chunkSize)

        const loadNext = () => {
            const start = currentChunk * chunkSize
            const end = Math.min(start + chunkSize, file.size)
            const chunk = file.slice(start, end)

            fileReader.onload = (e) => {
                spark.append(e.target?.result as ArrayBuffer)
                currentChunk++

                if (currentChunk < totalChunks) {
                    loadNext()
                } else {
                    resolve(spark.end())
                }
            }

            fileReader.onerror = reject
            fileReader.readAsArrayBuffer(chunk)
        }

        loadNext()
    })
}

/**
 * 上传分片
 */
const uploadChunk = async (chunk: Blob, uploadUrl: string) => {
    await axios.put(uploadUrl, chunk, {
        headers: {
            'Content-Type': 'application/octet-stream'
        }
    })
}

/**
 * 头像上传前的校验
 */
const beforeAvatarUpload = (file: File) => {
    // 检查文件类型
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        feedback.msgError('只能上传图片文件！')
        return false
    }

    // 检查文件大小（限制为10MB）
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
        feedback.msgError('图片大小不能超过10MB！')
        return false
    }

    return true
}

/**
 * 处理头像上传
 */
const handleAvatarUpload = async (options: UploadRequestOptions) => {
    const { file } = options
    
    try {
        avatarUploading.value = true
        
        // 计算文件MD5
        const fileMd5 = await calculateFileMD5(file as File)
        
        const chunkSize = 10 * 1024 * 1024 // 10MB分片大小
        const totalChunks = Math.ceil(file.size / chunkSize)
        
        // 准备上传参数
        const uploadParams = {
            filename: file.name,
            partCount: totalChunks,
            md5: fileMd5
        }
        
        // 初始化上传
        const initRes = await multipartInit(uploadParams)
        
        if (!initRes) {
            throw new Error('初始化上传失败')
        }
        
        const { uploadUrls, previewUrl } = initRes
        
        // 分片上传
        for (let i = 0; i < totalChunks; i++) {
            const start = i * chunkSize
            const end = Math.min(start + chunkSize, file.size)
            const chunk = file.slice(start, end)
            
            await uploadChunk(chunk, uploadUrls[i])
        }
        
        // 更新头像URL
        formData.avatar = previewUrl
        feedback.msgSuccess('头像上传成功！')
        
    } catch (error) {
        console.error('头像上传失败:', error)
        feedback.msgError('头像上传失败，请重试')
    } finally {
        avatarUploading.value = false
    }
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData
})
</script>

<style lang="scss" scoped>
.avatar-upload-container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;

    .avatar-preview {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        overflow: hidden;
        border: 1px solid #dcdfe6;

        .avatar-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }

    .avatar-placeholder {
        width: 80px;
        height: 80px;
        border: 2px dashed #dcdfe6;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #909399;
        font-size: 12px;

        p {
            margin: 4px 0 0 0;
        }
    }

    .avatar-uploader {
        :deep(.el-upload) {
            border: none;
        }
    }
}
</style>
